package net;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import types.Message;


public class StandardConnectionHandler implements ConnectionHandler {

	private Socket mSocket;
	private MessageReceivedListener mMessageReceivedListener;
	ObjectOutputStream oos;
	
	public StandardConnectionHandler(Socket socket, MessageReceivedListener messageReceivedListener) {
		mSocket = socket;
		mMessageReceivedListener = messageReceivedListener;
		
		try {
			OutputStream os = mSocket.getOutputStream();
			oos = new ObjectOutputStream(os);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		Thread read = new Thread(new Runnable() {
			
			@Override
			public void run() {

				try {
					InputStream is = mSocket.getInputStream();
					ObjectInputStream ois = new ObjectInputStream(is);

					
					while(mSocket.isConnected()) {
						Message m = (Message)ois.readObject();
						
						if(mMessageReceivedListener != null)
							mMessageReceivedListener.messageReceived(m);
					}
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		read.start();
	}
	
	public void sendMessage(Message message) throws IOException {
		
		oos.writeObject(message);
	}

	public void closeSocket() {
		try {
			mSocket.getInputStream().close();
			mSocket.getOutputStream().close();
			mSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public MessageReceivedListener getMessageReceivedListener() {
		return mMessageReceivedListener;
	}

	public void setMessageReceivedListener(MessageReceivedListener mMessageReceivedListener) {
		this.mMessageReceivedListener = mMessageReceivedListener;
	}
	
}
